package com.one.rope.mvp.web.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.one.rope.mvp.web.business.entity.AdminUser;
import com.one.rope.mvp.web.business.dao.AdminUserMapper;
import com.one.rope.mvp.web.business.service.IAdminUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.one.rope.mvp.web.common.auth.AdminUserInfo;
import com.one.rope.mvp.web.common.auth.TokenManager;
import com.one.rope.mvp.web.common.dto.admin.user.AdminUserLoginDTO;
import com.one.rope.mvp.web.common.dto.admin.user.AdminUserLoginVO;
import com.one.rope.mvp.basecore.bean.AdminBusinessMessage;
import com.one.rope.mvp.basecore.bean.ResponseObject;
import com.one.rope.mvp.basecore.exception.BusinessDataException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理后台用户表 服务实现类
 * </p>
 *
 * @author wesley
 * @since 2020-02-19
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements
    IAdminUserService {

  @Autowired
  TokenManager tokenManager;

  @Override
  public ResponseObject userLogin(AdminUserLoginDTO requestDTO) {
    AdminUser adminUser = this
        .getOne(new QueryWrapper<AdminUser>().eq("account", requestDTO.getAccount())
            .eq("password", requestDTO.getPassword()));
    if (null == adminUser) {
      throw new BusinessDataException(AdminBusinessMessage.ACCOUNT_OR_PWD_ERROR);
    }
    if (adminUser.getIsDelete() == 1) {
      throw new BusinessDataException(AdminBusinessMessage.ACCOUNT_BEEN_FORBIDEN);
    }
    // 登录成功
    AdminUserLoginVO loginVO = new AdminUserLoginVO();
    UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(requestDTO.getAccount(),
        requestDTO.getPassword());
    Subject subject = SecurityUtils.getSubject();
    subject.login(usernamePasswordToken);

    AdminUserInfo userInfo = new AdminUserInfo();
    userInfo.setUsernamePasswordToken(usernamePasswordToken);
    userInfo.setAdminUser(adminUser);
    String loginToken = tokenManager.saveAdminUserToken(userInfo);
    loginVO.setToken(loginToken);
    loginVO.setUserName(adminUser.getUserName());

    return new ResponseObject(loginVO);
  }

  @Override
  public ResponseObject userLogout() {
    return ResponseObject.successObject();
  }
}
